﻿package TaskStructure 
{
	import flash.display.MovieClip;
	import flash.events.Event;
		
	/** The highest level container for this project, a task wraps all items. */
	public class Task extends MovieClip
	{
		// private variables
		private var currentSection:int=0;
		private var startingProblemNumber:int;
		// private objects
		private var logWriter:LogWriter;
		private var taskFlowXML:XML, problemXML:XML, contextXML:XML, imagesXML:XML, errorsXML:XML;
		private var userID:String;
		private var sectionsxml:XMLList;
		private var section:Section;
		
		public function Task(userID:String, startingProblemNumber:int, taskFlowXML:XML, problemXML:XML, contextXML:XML, imagesXML:XML, errorsXML:XML)
		{
			this.userID = userID;
			this.startingProblemNumber = startingProblemNumber;
			this.taskFlowXML = taskFlowXML;
			this.problemXML = problemXML;
			this.contextXML = contextXML;
			this.imagesXML = imagesXML;
			this.errorsXML = errorsXML;
			this.addEventListener(Event.ADDED, handleAdded);
		}
		private function handleAdded (event:Event):void
		{
			this.removeEventListener(Event.ADDED, handleAdded);
			this.graphics.drawRect(0,0,this.parent.width, this.parent.height);
			// the log writer
			logWriter = new LogWriter(userID);			
			sectionsxml = taskFlowXML..section;
			// use starting problem number to figure out current section, and revise starting problem number
			// go through each section and see if starting problem number exceeds number of questions
			var problemCount:uint = 0;
			for (var i:uint=0; i < taskFlowXML..section.length(); i++)
			{
				var s:XML = taskFlowXML..section[i];
				// we found the problem to start at
				if (problemCount + s..item.length() >= startingProblemNumber)
				{
					currentSection = i;
					startingProblemNumber = startingProblemNumber - problemCount;
					break;
				} else 
				{
					problemCount += s..item.length();
				}
			}
			newSection();
		}
		/** Open a new section */
		private function newSection():void
		{
			trace("currentSection", currentSection, sectionsxml.length());
			if (currentSection < sectionsxml.length())
			{
				var isFinalFinal:Boolean = false;
				if (currentSection == sectionsxml.length()-1) isFinalFinal = true;
				section = new Section(logWriter, startingProblemNumber, sectionsxml[currentSection], problemXML, contextXML, imagesXML, errorsXML, isFinalFinal);
				section.addEventListener(Event.COMPLETE, handleSectionComplete);
				this.addChild(section);
			} else
			{
				this.dispatchEvent(new Event(Event.COMPLETE));				
			}			
		}
		/** The section is complete, iterate and try another */
		private function handleSectionComplete(event:Event):void
		{
			section.removeEventListener(Event.COMPLETE, handleSectionComplete);
			this.removeChild(section);
			currentSection++;
			startingProblemNumber = 1;
			newSection();
		}
	}
}